package com.stox.client.ui.javafx.widget.dynamic.column.barValue;

import java.util.List;

import javafx.beans.property.ObjectProperty;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;

import com.stox.client.api.data.provider.BarClient;
import com.stox.client.ui.javafx.widget.dynamic.column.AbstractCellValueFactory;
import com.stox.client.ui.javafx.widget.dynamic.column.AbstractColumn;
import com.stox.shared.core.i18n.MessageSource;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.enumeration.BarSpan;
import com.stox.shared.core.model.filter.BarCriteria;
import com.stox.shared.core.model.intf.HasScrip;

public class VolumeColumn<S extends HasScrip> extends AbstractColumn<S, Double> {
	
	private BarSpan barSpan = BarSpan.DAILY;
	
	public VolumeColumn(final BarClient barClient) {
		setText(MessageSource.get("Volume"));
		setPrefWidth(60);
		setMaxWidth(60);
		setMinWidth(60);

		setCellFactory(new Callback<TableColumn<S,Double>, TableCell<S,Double>>() {
			@Override
			public TableCell<S, Double> call(TableColumn<S, Double> param) {
				return new TableCell<S, Double>(){
					@Override
					protected void updateItem(Double item, boolean empty) {
						super.updateItem(item, empty);
						if(null == item || empty){
							setText(null);
						}else{
							setText(String.valueOf(item.longValue()));
						}
					}
				};
			}
		});
		
		setCellValueFactory(new AbstractCellValueFactory<S, Double>(){
			@Override
			public void fetchValue(
					final javafx.scene.control.TableColumn.CellDataFeatures<S, Double> cellDataFeatures,
					final ObjectProperty<Double> valueProperty) {
				new Thread(){
					public void run() {
							S hasScrip = cellDataFeatures.getValue();
							if(null != hasScrip && null != hasScrip.getScrip() && null != hasScrip.getScrip().getId()){
								List<Bar> bars =barClient.find(new BarCriteria(hasScrip.getScrip().getId(), barSpan.previous(), barSpan.next(), barSpan));
								if(null != bars && !bars.isEmpty()){
									valueProperty.set(bars.get(0).getVolume());
								}
							}
					};
				}.start();
			}
		});
	
	}
	
	@Override
	public void configure() {
		

	}

}
